package demo.BlockingQueueDemo;

import java.util.Random;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * Created by zhangyanfei on 2018/4/12.
 * @author zhangyanfei
 * @date 2018/04/12
 */
public class Producer implements Runnable {
    //线程共享
    private volatile boolean isRunning = true;
    private BlockingQueue<PcData> queue;
    private static AtomicInteger count = new AtomicInteger();//总数 原子操作
    private static final int SLEEPTIME = 1000;

    public Producer(BlockingQueue<PcData> queue) {
        this.queue = queue;
    }

    @Override
    public void run() {
        PcData pcData = null;
        Random r = new Random();
        System.out.println("start producting id:" + Thread.currentThread().getId());
        try {
            while (isRunning) {
                Thread.sleep(r.nextInt(SLEEPTIME));
                pcData = new PcData(count.incrementAndGet());
                queue.add(pcData);
                System.out.println(pcData);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            Thread.currentThread().interrupt();
        }
    }

    public void stop() {
        isRunning = false;
    }
}
